<template>
  <div>
     <van-cell @click="onClickItem(item)" v-for="(item,index) in suggestions" :key="index"  icon="search" >
       <template #title>
         <div v-html="formatStr(item)"></div>
       </template>
     </van-cell>
     <!-- 搜索提示 -->
       <van-empty v-if="!suggestions.length" image="search" description="暂无建议" />
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search.js'
import { Toast } from 'vant'
export default {
  props: {
    // 1要根据输入框的值 获取 搜索建议
    // 接受父组件输入框的值
    searchText: {
      type: String,
      required: true
    }
  },
  watch: {
    // 监视父组件输入框值得变化
    searchText: {
      immediate: true, // 首次监听
      handler (newVal) {
        this.setId && clearTimeout(this.setId)
        this.setId = setTimeout(() => {
          this.loadSearchSuggestion()
        }, 800)
      }
    }
  },
  data () {
    return {
      suggestions: []

    }
  },

  created () {

  },
  // 组件销毁前把定时器清掉
  beforeDestroy () {
    clearTimeout(this.setId)
  },
  methods: {
    // 加载搜索建议
    async loadSearchSuggestion () {
      try {
        const { options: res } = await getSearchSuggestion(this.searchText)
        this.suggestions = res
      } catch (err) {
        Toast('获取联想建议失败')
      }
    },
    // 处理文字高亮
    formatStr (str) {
      const reg = new RegExp(this.searchText, 'gi')
      return str.replace(reg, `<span style="color:red">${this.searchText}</span>`)
    },
    onClickItem (item) {
      this.$emit('clickItem', item)
    }
  }
}
</script>

<style scoped>

</style>
